import { parsePath } from './util'
import Dep from './Dep';
var uid = 0;
export default class Watcher {
    constructor(target, expression, callback) {
        console.log("我是Watcher");
        this.id = uid++;
        this.target = target;
        this.getter = parsePath(expression);
        this.callback = callback;
        this.value = this.get();
    };
    update() {
        this.run();
    };

    get() {
        //进入依赖收集阶段，让全局变量Dep.target设置为Watcher本身
        Dep.target = this;
        const obj = this.target;
        var value;
        try {
            value = this.getter(obj);
        } catch (error) {
            throw new Error(error);
        } finally {
            Dep.target = null;
        }
        return value;
    };

    run() {
        this.getAndInvoke(this.callback);
    };

    getAndInvoke(callback) {
        const value = this.get();

        if (this.value !== value || (typeof value == 'object')) {
            const oldValue = this.value;
            this.value = value;
            callback.call(this.target, value, oldValue);

        }
        return value;
    }
}